package edu.gyc.book.controller;

import edu.gyc.book.model.Book;
import edu.gyc.book.model.Category;
import edu.gyc.book.service.BookService;
import edu.gyc.book.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LibraryController {
    @Autowired
    CategoryService categoryService;

    @RequestMapping("/category")
    public String index(Model model) {
        List<Category> categories = categoryService.getCategoryList();
        model.addAttribute("cates", categories);
        return "category";
    }

    @Autowired
    BookService bookService;

    @GetMapping("/list")
    public String list(Integer id, Model model) {
        List<Book> books = bookService.getBooksByCid(id);
        if (books.size() > 0) {
            model.addAttribute("books", books);
            model.addAttribute("category", books.get(0).getCategory());
        }else {
            //分类无图书，需要给添加书籍提供分类信息
            Category category = categoryService.getCategoryById(id);
            model.addAttribute("msg", "该图书分类暂时没有书籍，欢迎捐赠和捐款！");
            model.addAttribute("category", category);
        }

        return "/book";
    }

    @PostMapping("/book/add")
    public String add(Book book, HttpServletRequest request) {
        String msg = "";
      boolean r=  bookService.addBook(book);
        if (r) {
           msg=book.getTitle()+"添加成功！";

        }else {
            msg=book.getTitle()+"添加失败，Isbn重复！";
        }
        request.setAttribute("msg",msg);
        return "/msg";
    }

    @PostMapping("/book/update")
    public String update(Book book, HttpServletRequest request) {
        String msg = "";
        boolean r=  bookService.updateBook(book);
        if (r) {
            msg="更新ISBN号为"+book.getIsbn()+"的书籍信息成功！";

        }else {
            msg="更新ISBN号为"+book.getIsbn()+"的书籍失败，Isbn重复！";
        }
        request.setAttribute("msg",msg);
        return "/msg";
    }

    @GetMapping("/book/del")
    public String del(Integer id, HttpServletRequest request) {
        String msg = "";
        boolean r=  bookService.deleteBook(id);
        if (r) {
            msg="删除书籍信息成功！";

        }else {
            msg="删除书籍失败！";
        }
        request.setAttribute("msg",msg);
        return "/msg";
    }

}
